from celery import shared_task
from django.utils import timezone
from .models import Host, HostPassword, City, DataCenter, CityHostStatistics, IDCHostStatistics
from .serializers import generate_random_password
from datetime import date, timedelta
from celery import shared_task
from .models import Host
import random
import logging
from datetime import datetime, timedelta
from django.utils.timezone import now
from django.db.models import Count

@shared_task
def update_all_host_passwords():
    hosts = Host.objects.all()
    for host in hosts:
        update_host_password.delay(host.id)


@shared_task
def update_host_password(host_id):
    from .models import HostPassword

    host = Host.objects.filter(id=host_id).first()
    new_password = generate_random_password()

    try:
        password_obj = HostPassword.objects.get(host=host)
        # 保存历史密码
        history = password_obj.history or []
        history.append({
            'password': password_obj.root_password,
            'changed_at': timezone.now().isoformat()
        })
        password_obj.root_password = new_password
        password_obj.history = history[-10:]  # 只保留最近10次记录
        password_obj.save()
    except HostPassword.DoesNotExist:
        HostPassword.objects.create(
            host=host,
            root_password=new_password,
            history=[]
        )




@shared_task
def generate_daily_statistics():
    city_stats = Host.objects.values('data_center__city__name').annotate(
        count=Count('id')
    ).order_by('data_center__city__name')

    # 按机房统计
    data_center = Host.objects.values('data_center__name', 'data_center__city__name').annotate(
        count=Count('id')
    ).order_by('data_center__city__name', 'data_center__name')

    for stat in city_stats:
        city_name = stat['data_center__city__name']
        city = City.objects.filter(name=city_name).first()
        if not city:
            return {"城市不存在"}
        stats, created = CityHostStatistics.objects.get_or_create(
            city=city,
            date=now().date(),
            defaults={'host_count': stat['count']}
        )
        if not created:
            stats.host_count = stat['count']
            stats.save(update_fields=['host_count'])

    for stat in data_center:
        idc_name = stat['data_center__name']
        city_name = stat['data_center__city__name']
        idc = DataCenter.objects.filter(name=idc_name, city__name=city_name).first()
        if not idc:
            return {"机房不存在"}
        stats, created = IDCHostStatistics.objects.get_or_create(
            idc=idc,
            date=now().date(),
            defaults={'host_count': stat['count']}
        )
        if not created:
            stats.host_count = stat['count']
            stats.save(update_fields=['host_count'])

    return {
        'city_stats_count': len(city_stats),
        'idc_stats_count': len(data_center)
    }